<template>
  <div class="bg-white p-4 rounded-lg shadow-lg">
    <h2 class="text-lg font-bold mb-4">修改</h2>
    <el-form
      :model="formData"
      label-width="auto"
      label-position="top"
      :rules="rulesForm"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入标题"
          class="mb-4"
        />
      </el-form-item>
      <el-form-item label="封面" prop="cover">
        <Upload v-model="formData.cover" :limit="1" hiddenCard />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <div class="w-full">
          <Editor v-model="formData.content" />
        </div>
      </el-form-item>
      <el-button type="primary" @click="onSubmit">提交</el-button>
    </el-form>
  </div>
</template>
<script setup>
import Editor from "@/components/Editor/index.vue";
import Upload from "@/components/Upload/index.vue";
import { ref } from "vue";
import { useDetail } from "./hooks";
import { getNewsDetail, NewEdit } from "@/api/information";
import { message } from "@/utils/message";
defineOptions({
  name: "newEdit"
});

const { initToDetail, getParameter } = useDetail();
initToDetail("query");

const formData = ref({
  title: "",
  cover: [],
  content: ""
});
// 新闻详情
let newInfo = ref({});
if (getParameter.news_id) {
  getNewsDetail({ news_id: getParameter.news_id })
    .then(res => {
      newInfo.value = res.data;
      const { title, cover, content } = res.data;
      formData.value = {
        title,
        cover: [{ name: title, url: cover }],
        content
      };
    })
    .catch(err => {
      console.error("错误", err);
    });
}
// 表单校验
const rulesForm = ref({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  cover: [{ required: true, message: "请上传封面", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }]
});
const onSubmit = () => {
  const { title, cover, content } = formData.value;
  let parmas = {
    ...formData.value,
    cover: cover[0].url
  };
  if (getParameter.news_id) {
    parmas.news_id = getParameter.news_id;
  }
  NewEdit(parmas)
    .then(res => {
      if (res.code == 1) {
        message("更新成功", { customClass: "el", type: "success" });
      } else {
        message("更新失败", { customClass: "el", type: "error" });
      }
    })
    .catch(err => {
      message("更新失败", { customClass: "el", type: "error" });
      console.error("更新失败", err);
    });
};
</script>
<style scoped lang="scss">
:deep(.disabled .el-upload--picture-card) {
  display: none;
}
</style>
